<template>
  <div>
    <el-input
        v-model="internalValue"
        @input="handleInput"
        :placeholder="placeholder"
        :min="min"
        :max="max"
        type="number"
        @keypress="isNumber($event)"
    />
  </div>
</template>

<script>
export default {
  name: 'NumberInput',
  props: {
    value: [Number, String],
    min: {
      type: Number,
      default: -Infinity
    },
    max: {
      type: Number,
      default: Infinity
    },
    placeholder: {
      type: String,
      default: '请输入数字'
    },
  },
  data() {
    return {
      internalValue: this.processInput(this.value) // 组件内部的值，用于v-model绑定
    };
  },
  methods: {
    handleInput(value) {
      this.$emit('input', value); // 当输入时，向父组件发出input事件
    },
    isNumber(evt) {
      // 阻止非数字的输入
      evt = (evt) ? evt : window.event;
      var charCode = (evt.which) ? evt.which : evt.keyCode;
      // 允许数字、小数点、删除键、箭头键
      if ((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode !== 46) {
        evt.preventDefault();
      } else {
        return true;
      }
    },
    processInput(value) {
      // 尝试把value处理为数值
      if (typeof value === 'string') {
        return isNaN(Number(value)) ? 0 : Number(value);
      }
      return value;
    }
  },
  watch: {
    value(val) {
      val = this.processInput(val);

      if (val < this.min) {
        this.internalValue = this.min;
      } else if (val > this.max) {
        this.internalValue = this.max;
      } else {
        this.internalValue = val;
      }
    },
    internalValue(val) {
      if (val < this.min) {
        this.internalValue = this.min;
        this.$emit('input', this.min);
      } else if (val > this.max) {
        this.internalValue = this.max;
        this.$emit('input', this.max);
      }
    }
  }
};
</script>